// pages/cart/cart.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    carts: [],
    hidden: true,
    priceNum: 0,
    showPrice: 0,
    allCheck: true
  },
  //结算
  settleAccounts: function (e) {
    var that = this
    wx.requestPayment({
      timeStamp: '',
      nonceStr: '',
      package: 'prepay_id=1',
      signType: 'MD5',
      paySign: '',
      success(res) {},
      fail(res) {
        console.log('2')
        wx.showToast({
          title: '支付成功',
          icon: 'success',
          duration: 2000,
          complete(res) {
            var arr = wx.getStorageSync('isBuy') || []
            for (var j = 0;j< that.data.carts.length;j++) {
              if (that.data.carts[j].isCheck) {
                arr.unshift(that.data.carts[j])
                that.data.carts.splice(j, 1)
                j = j-1
              }
            }
            that.setData({carts:that.data.carts})
            wx.setStorageSync('cart',that.data.carts)
            wx.setStorageSync('isBuy', arr)
            //跳到订单页
            wx.navigateTo({
              url: '../orderForm/orderForm'
            })
          }
        })
      }
    })
  },
  //删除
  delpro: function (e) {
    var that = this
    if (that.data.carts.length == 0) {
      return
    }
    for (var i = 0; i < that.data.carts.length; i++) {
      if (that.data.carts[i].isCheck) {
        wx.showModal({
          title: '提示',
          content: '确定将选中的商品移出购物车吗？',
          success(res) {
            if (res.confirm) {
              for (var i = 0; i < that.data.carts.length; i++) {
                if (that.data.carts[i].isCheck) {
                  that.data.carts.splice(i, 1)
                  // 使用splice方法删除会使后面的数据位置前进 1（删除的数量）
                  i = i - 1
                }
              }
              that.setData({
                carts: that.data.carts
              })
              wx.setStorageSync('cart', that.data.carts);
              that.priceCount()
            } else if (res.cancel) {
              return
            }
          }
        })
        break
      }
    }


  },
  //全选
  allChecked: function (e) {
    if (!this.data.allCheck) {
      this.data.priceNum = 0
      for (var i = 0; i < this.data.carts.length; i++) {
        this.data.carts[i].isCheck = true
        this.data.priceNum = this.data.priceNum + (parseFloat(this.data.carts[i].price) * parseFloat(this.data.carts[i].count))
      }
    } else {
      for (var i = 0; i < this.data.carts.length; i++) {
        this.data.carts[i].isCheck = false
      }
      this.data.priceNum = 0
    }
    this.data.showPrice = this.data.priceNum.toFixed(2)
    this.setData({
      carts: this.data.carts,
      allCheck: !this.data.allCheck,
      priceNum: this.data.priceNum,
      showPrice: this.data.showPrice
    })
    wx.setStorageSync('cart', this.data.carts);
  },
  //选中/取消选中
  check: function (e) {
    var allPrice = 0;
    var index = e.target.dataset.index
    // console.log(index)
    // console.log(this.data.carts)

    this.data.carts[index].isCheck = !this.data.carts[index].isCheck
    if (this.data.carts[index].isCheck) {
      this.data.priceNum = this.data.priceNum + (parseFloat(this.data.carts[index].price) * parseFloat(this.data.carts[index].count))
    } else {
      this.data.priceNum = this.data.priceNum - (parseFloat(this.data.carts[index].price) * parseFloat(this.data.carts[index].count))
    }
    for (var i = 0; i < this.data.carts.length; i++) {
      allPrice = allPrice + (parseFloat(this.data.carts[i].price) * parseFloat(this.data.carts[i].count))
    }
    if (allPrice == this.data.priceNum) {
      this.data.allCheck = true
    } else {
      this.data.allCheck = false
    }
    this.data.showPrice = this.data.priceNum.toFixed(2)
    this.setData({
      carts: this.data.carts,
      allCheck: this.data.allCheck,
      priceNum: this.data.priceNum,
      showPrice: this.data.showPrice
    })
    wx.setStorageSync('cart', this.data.carts);
    console.log(this.data.priceNum, this.data.allCheck, allPrice)
  },
  //计算价格
  priceCount: function (e) {
    this.data.priceNum = 0
    for (var i = 0; i < this.data.carts.length; i++) {
      if (this.data.carts[i].isCheck) {
        this.data.priceNum = this.data.priceNum + (parseFloat(this.data.carts[i].price) * parseFloat(this.data.carts[i].count))
      }
    }
    this.data.showPrice = this.data.priceNum.toFixed(2)
    this.setData({
      priceNum: this.data.priceNum,
      showPrice: this.data.showPrice
    })
  },
  //赠加购买数量
  add: function (e) {
    var index = e.target.dataset.index
    console.log(index, "+")
    this.data.carts[index].count++
    // 将数值与状态写回 
    this.setData({
      carts: this.data.carts
    })
    wx.setStorageSync('cart', this.data.carts);
    // console.log("+",this.data.carts)
    this.priceCount()
  },
  //减少购买数量
  sub: function (e) {
    var index = e.target.dataset.index
    console.log(index, "-")
    if (this.data.carts[index].count > 1) {
      this.data.carts[index].count--
    }
    // 将数值与状态写回 
    this.setData({
      carts: this.data.carts
    })
    wx.setStorageSync('cart', this.data.carts);
    this.priceCount()
  },
  toShopping: function (e) {
    wx.switchTab({
      url: '../classify/classify'
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {},

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {},

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var arr = wx.getStorageSync('cart') || [];
    if (arr.length > 0) {
      if (!arr[0].hasOwnProperty('isCheck')) {
        for (var j in arr) {
          arr[j].isCheck = true
        }
      }
      for (var j in arr) {
        if (arr[j].isCheck) {

        } else {
          this.data.allCheck = false
          break
        }
      }
      // 更新数据  
      this.setData({
        carts: arr,
        hidden: false,
        allCheck: this.data.allCheck
      });
      this.priceCount()
    } else {
      this.setData({
        hidden: true,
      });
    }

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})